package com.hertz.iris.view.alarm;

import java.util.Calendar;

import javax.inject.Inject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
import butterknife.InjectView;
import butterknife.OnClick;

import com.hertz.iris.Injector;
import com.hertz.iris.IrisApplication;
import com.hertz.iris.R;
import com.hertz.iris.core.NormalAlarmService;
import com.hertz.iris.pojo.NormalAlarm;
import com.hertz.iris.ui.IrisFragmentActivity;
import com.hertz.iris.util.BundleKeys;
import com.hertz.iris.util.Constants;
import com.hertz.iris.util.Strings;
import com.hertz.iris.util.Utils;
import com.hertz.iris.view.alarm.HHMMSelectorFragment.OnSetHM;
import com.hertz.iris.view.alarm.LoopSelectorFrag.OnLoopSelectLisener;
import com.hertz.iris.view.alarm.RingSelectorFrag.OnRingSelectorListener;
import com.hertz.iris.view.alarm.VolumeSelectorFrag.OnVolumeSelectListener;

public class NormalAlarmActivity extends IrisFragmentActivity implements OnLoopSelectLisener,OnVolumeSelectListener,OnRingSelectorListener,OnSetHM{
	
	@InjectView(R.id.alarm_name_text)
	TextView alarmNameText;
	@InjectView(R.id.snooze_text) 
	TextView snoozeText;
	@InjectView(R.id.ring_ll)
	LinearLayout ringLL;
	@InjectView(R.id.ring)
	TextView ringText;
	@InjectView(R.id.volume_ll)
	LinearLayout volumeLL;
	@InjectView(R.id.volume)
	TextView volumeText;
	@InjectView(R.id.wave_tb)
	ToggleButton waveTb;
	@InjectView(R.id.cancel_btn)
	Button cancelBtn;
	@InjectView(R.id.ok_btn)
	Button okBtn;
	@InjectView(R.id.trash_btn)
	Button trashBtn;
	//loop
	@InjectView(R.id.loop_ll)
	LinearLayout loopLL;
	@InjectView(R.id.loop_value_text)
	TextView loopValueText;
	
	@Inject protected NormalAlarmService normalAlarmService;
	
	private String[] weeks;
	private String[] snoozeValues;
	private int[] snoozes;
	
	private NormalAlarm normalAlarm;
	
	//
	private String currentFragmentTag;
	private String CUR_FRAG_TAG_KEY = "currentFragmentTagKey";
	
	private Bundle arguments = new Bundle();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.normal_alarm);
		Injector.inject(this);
		initAlarmValue(savedInstanceState);
		initView();
	}
	
	private void initAlarmValue(Bundle savedInstanceState){
		weeks = getResources().getStringArray(R.array.weeks);
		snoozeValues = getResources().getStringArray(R.array.snooze_values);
		snoozes = getResources().getIntArray(R.array.snoozes);
		Intent intent = getIntent();
		if(intent != null && intent.getSerializableExtra(BundleKeys.NormalAlarmBundleKeys.NORMAL_ALARM_KEY) != null){
			normalAlarm = (NormalAlarm)intent.getSerializableExtra(BundleKeys.NormalAlarmBundleKeys.NORMAL_ALARM_KEY);
			currentFragmentTag = TimeFragment.class.getSimpleName();
			return;
		}
		if(savedInstanceState != null){
			normalAlarm = (NormalAlarm)savedInstanceState.getSerializable(BundleKeys.NormalAlarmBundleKeys.NORMAL_ALARM_KEY);
			currentFragmentTag = savedInstanceState.getString(CUR_FRAG_TAG_KEY);
		}else{
			Calendar c = Calendar.getInstance();
			normalAlarm = new NormalAlarm();
			normalAlarm.setHh(Integer.valueOf(c.get(Calendar.HOUR_OF_DAY)).byteValue());
			normalAlarm.setMm(Integer.valueOf(c.get(Calendar.MINUTE)).byteValue());
			normalAlarm.setRingName(getResources().getString(R.string.no_ring));
			normalAlarm.setWave(Constants.NORMAL_ALARM.DEFAULT_WAVE);
			normalAlarm.setVolume(Constants.NORMAL_ALARM.DEFAULT_VALUME);
			normalAlarm.setWeeks(Constants.NORMAL_ALARM.DEFAULT_WEEKS);
			normalAlarm.setSnooze(Constants.NORMAL_ALARM.DEFAULT_SNOOZE);
			currentFragmentTag = TimeFragment.class.getSimpleName();
		}
	}
	
	private Bundle getArguments(){
		arguments.putSerializable(BundleKeys.NormalAlarmBundleKeys.NORMAL_ALARM_KEY, normalAlarm);
		arguments.putString(CUR_FRAG_TAG_KEY, currentFragmentTag);
		return arguments;
	}
	
	private void initView(){
		
		cancelBtn.setTypeface(IrisApplication.getInstance().getTypeface());
		okBtn.setTypeface(IrisApplication.getInstance().getTypeface());
		trashBtn.setTypeface(IrisApplication.getInstance().getTypeface());
		if(normalAlarm.getId() == null){
			trashBtn.setVisibility(View.GONE);
		}
		if(!Strings.isBlank(currentFragmentTag)){
			try {
				replaceFragment(Class.forName(this.getClass().getPackage().getName() + "." + currentFragmentTag));
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
        
        loopValueText.setText(getLoopValue());
        
        int snoozeIndex = normalAlarm.getSnooze() % snoozeValues.length; 
        snoozeText.setText(String.format(snoozeValues[snoozeIndex],snoozes[snoozeIndex]));
        
        volumeText.setText(normalAlarm.getVolume() + "%");
        ringText.setText(normalAlarm.getRingName());
        alarmNameText.setText(normalAlarm.getName());
        waveTb.setChecked(normalAlarm.getWave());
        initSelected();
//        alarmNameText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//			
//			@Override
//			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//				if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)){  
//                	v.setInputType(InputType.TYPE_NULL);
//                }  
//                return false;  
//			}
//		});
	}
	
	void replaceFragment(Class fragClass) {
		alarmNameText.clearFocus();
		FragmentManager fm = getSupportFragmentManager();
		Fragment fragment = fm.findFragmentByTag(fragClass.getSimpleName());
		FragmentTransaction ft = fm.beginTransaction();
        ft.setCustomAnimations(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
        try {
			fragment = (Fragment)fragClass.newInstance();
			fragment.setArguments(getArguments());
			ft.replace(R.id.newalarm_fragment_container,fragment, fragClass.getSimpleName());
			currentFragmentTag = fragClass.getSimpleName();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
        ft.commit();
	}
	
	@Override
	public void onSaveInstanceState(Bundle bundle){
		super.onSaveInstanceState(bundle);
		bundle.putAll(getArguments());
	}
	
	@OnClick(R.id.loop_ll)
	void loopLLOnClick() {
		if(loopLL.isSelected()){
			loopLL.setSelected(false);
			replaceFragment(TimeFragment.class);
		}else{
			loopLL.setSelected(true);
			replaceFragment(LoopSelectorFrag.class);
		}
		clearOtherSelectedState(R.id.loop_ll);
	}

	@OnClick(R.id.snooze_ll)
	void snoozeLLOnClick(){
		Integer index = (normalAlarm.getSnooze()+1) % snoozeValues.length;
		normalAlarm.setSnooze(index.byteValue());
		snoozeText.setText(String.format(snoozeValues[index],snoozes[index]));
	}
	
	@OnClick(R.id.volume_ll)
	void volumeLLOnClick(){
		if(volumeLL.isSelected()){
			volumeLL.setSelected(false);
			replaceFragment(TimeFragment.class);
		}else{
			volumeLL.setSelected(true);
			replaceFragment(VolumeSelectorFrag.class);
		}
		clearOtherSelectedState(R.id.volume_ll);
	}
	@OnClick(R.id.ring_ll)
	void ringLLOnClick(){
		if(ringLL.isSelected()){
			ringLL.setSelected(false);
			replaceFragment(TimeFragment.class);
		}else{
			ringLL.setSelected(true);
			replaceFragment(RingSelectorFrag.class);
		}
		clearOtherSelectedState(R.id.ring_ll);
	}
	@OnClick(R.id.wave_tb)
	void waveToggleButtonOnClick(){
		if(waveTb.isChecked()){
			Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);  
			vibrator.vibrate(500); 
		}
		normalAlarm.setWave(waveTb.isChecked());
	}
	
	@OnClick(R.id.trash_btn)
	void trashBtnClick(){
		normalAlarmService.deleteNormalAlarm(normalAlarm.getId());
		super.onBackPressed();
	}
	
	@OnClick(R.id.cancel_btn)
	void cancelBtnClick(){
		super.onBackPressed();
	}
	
	@OnClick(R.id.ok_btn)
	void okBtnClick(){
		normalAlarm.setUtime(System.currentTimeMillis());
		normalAlarm.setName(alarmNameText.getText().toString());
		normalAlarm.setIsActive(true);
		if(normalAlarm != null && normalAlarm.getId() == null){//update
			normalAlarm.setCtime(System.currentTimeMillis());
			normalAlarmService.saveAlarm(normalAlarm);
		}else{
			normalAlarmService.updateNormalAlarm(normalAlarm);
		}
		super.onBackPressed();
	}
	
	@Override
	public void loopSelectListener(byte[] values) {
		normalAlarm.setWeeks(Utils.byteWeekValues2String(values));
		loopValueText.setText(getLoopValue());
	}
	
	@Override
	public void ringSelectorListener(byte index,String title, String uri) {
		ringText.setText(title);
		normalAlarm.setRingName(title);
		normalAlarm.setRingUri(uri);
	}

	@Override
	public void volumeSelectListener(byte volumeValue) {
		volumeText.setText(String.format(getResources().getString(R.string.volume),volumeValue));
		normalAlarm.setVolume(volumeValue);
	}

	@Override
	public void setHM(byte hh,byte mm){
		FragmentManager fm = getSupportFragmentManager();
		TimeFragment timeFragment = (TimeFragment)fm.findFragmentByTag(TimeFragment.class.getSimpleName());
		timeFragment.setHM(hh, mm);
		normalAlarm.setHh(hh);
		normalAlarm.setMm(mm);
	}
	
	@Override
	public void onBackPressed() {
		FragmentManager fm = getSupportFragmentManager();
		Fragment hhmmSlectorFrag = fm.findFragmentByTag(HHMMSelectorFragment.class.getSimpleName());
		if(hhmmSlectorFrag != null){
			fm.beginTransaction().remove(hhmmSlectorFrag).commit();
		}else if(currentFragmentTag.equals(TimeFragment.class.getSimpleName()) && hhmmSlectorFrag == null)
			super.onBackPressed();
		else{
			replaceFragment(TimeFragment.class);
	        
	        loopLL.setSelected(false);
	        volumeLL.setSelected(false);
	        ringLL.setSelected(false);
		}
	}

	private void clearOtherSelectedState(int viewId){
		if(viewId != loopLL.getId()){
			loopLL.setSelected(false);
		}
		if(viewId != volumeLL.getId()){
			volumeLL.setSelected(false);
		}
		if(viewId != ringLL.getId()){
			ringLL.setSelected(false);
		}
	}
	
	private String getLoopValue(){
		StringBuffer sb = new StringBuffer();
		byte[] weekValues = Utils.string2byteArr(normalAlarm.getWeeks(), ",");
		for(int i = 0; i < weekValues.length; i++){
			if(weekValues[i] == 1){
				sb.append(weeks[i]).append(" ");
			}
		}
		return sb.toString();
	}
	
	private void initSelected(){
		if(currentFragmentTag.equals(TimeFragment.class.getSimpleName())){
			return;
		}
		if(currentFragmentTag.equals(LoopSelectorFrag.class.getSimpleName())){
			loopLL.setSelected(true);
			return;
		}
		if(currentFragmentTag.equals(RingSelectorFrag.class.getSimpleName())){
			ringLL.setSelected(true);
			return;
		}
		if(currentFragmentTag.equals(VolumeSelectorFrag.class.getSimpleName())){
			volumeLL.setSelected(true);
			return;
		}
	}
	
}
